import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../../common/api/index.dart';
import '../../../../common/models/index.dart';
import '../../../../common/utils/index.dart';
import '../../../../common/values/index.dart';
import '../../../../common/widgets/index.dart';
import '../../../common/process_webview/index.dart';
import 'index.dart';

class OfficeCenterController extends GetxController {
  OfficeCenterController();

  final state = OfficeCenterState();
  final refreshController = RefreshController();
  final TextEditingController searchController = TextEditingController();

  String? _type;
  String _lastId = O2.o2DefaultPageFirstKey;
  bool isLoading = false; // 防止重复刷新
  bool isRefresh = true; // 刷新还是加载更多

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    final type = Get.parameters['type'];
    _type = type;
    var title = '';
    if (O2NativeAppEnum.task.key == type) {
      title = O2NativeAppEnum.task.name;
    } else if (O2NativeAppEnum.taskcompleted.key == type) {
      title = O2NativeAppEnum.taskcompleted.name;
    } else if (O2NativeAppEnum.read.key == type) {
      title = O2NativeAppEnum.read.name;
    } else if (O2NativeAppEnum.readcompleted.key == type) {
      title = O2NativeAppEnum.readcompleted.name;
    }
    state.title = Get.parameters['displayName'] ?? title;
    
    onRefresh();
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  onRefresh() async {
    if (_type == null) return;
    if (isLoading) return;
    _lastId = O2.o2DefaultPageFirstKey;
    isRefresh = true;
    state.hasMoreData = true;

    await loadDataFromServer();
    refreshController.refreshCompleted();
  }

  onLoadMore() async {
    if (isLoading) return;
    if (!state.hasMoreData) {
      refreshController.loadComplete();
      return;
    }
    isRefresh = false;

    await loadDataFromServer();
    refreshController.loadComplete();
  }

  ///
  /// 搜索
  ///
  void onSearch(String key) {
    OLogger.d("搜索关键字：$key");
    onRefresh();
  }

  Future<void> clickTask(TaskData task) async {
    if (task.work != null && task.work?.isNotEmpty == true) {
      await ProcessWebviewPage.open(task.work!,
          title: task.title ??
              'process_work_no_title'.trArgs(['${task.processName}']));
      onRefresh();
    }
  }

  void clickTaskCompleted(TaskCompletedData taskcompleted) async {
    Loading.show();
    final reference = await ProcessSurfaceService.to
        .getTaskCompletedReference(taskcompleted.id!);
    if (reference != null) {
      Loading.dismiss();
      openReference(reference.workLogList ?? [], taskCompleted: taskcompleted);
    }
  }

  void clickRead(ReadData read) async {
    Loading.show();
    final reference = await ProcessSurfaceService.to.getReadReference(read.id!);
    if (reference != null) {
      Loading.dismiss();
      openReference(reference.workLogList ?? [], read: read);
    }
  }

  void clickReadCompleted(ReadCompletedData readcompleted) async {
    Loading.show();
    final reference = await ProcessSurfaceService.to
        .getReadCompletedReference(readcompleted.id!);
    if (reference != null) {
      Loading.dismiss();
      openReference(reference.workLogList ?? [], readCompleted: readcompleted);
    }
  }

  /// 展现 workLog 列表
  void openReference(List<WorkLog> workLogList,
      {TaskCompletedData? taskCompleted,
      ReadData? read,
      ReadCompletedData? readCompleted}) {
    final context = Get.context;
    if (context != null) {
      String title = '';
      String detailTitle = '';
      String detailActiviyName = '';
      Work work = Work();
      if (taskCompleted != null) {
        title = 'process_taskcompleted_detail_title'.tr;
        detailTitle = '[${taskCompleted.processName}] ${taskCompleted.title}';
        detailActiviyName = '${taskCompleted.activityName}';
        work.id = taskCompleted.work;
        work.title = taskCompleted.title;
        work.processName = taskCompleted.processName;
      } else if (read != null) {
        title = 'process_read_detail_title'.tr;
        detailTitle = '[${read.processName}] ${read.title}';
        detailActiviyName = '${read.activityName}';
        work.id = read.work;
        work.title = read.title;
        work.processName = read.processName;
      } else if (readCompleted != null) {
        title = 'process_readcompleted_detail_title'.tr;
        detailTitle = '[${readCompleted.processName}] ${readCompleted.title}';
        detailActiviyName = '${readCompleted.activityName}';
        work.id = readCompleted.work;
        work.title = readCompleted.title;
        work.processName = readCompleted.processName;
      } else {
        return;
      }

      WorkLog? endLog;
      for (var element in workLogList) {
        if (element.arrivedActivityType == 'end') {
          endLog = element.copywith();
          endLog.isEnd = true;
          break;
        }
      }
      if (endLog != null) {
        workLogList.add(endLog);
      }

      showModalBottomSheet(
          context: context,
          shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(10.0),
                topRight: Radius.circular(10.0)),
          ),
          builder: ((context) {
            return Padding(
                padding: const EdgeInsets.all(10),
                child: Container(
                    height: 350.0,
                    color: Colors.transparent,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Padding(
                            padding: const EdgeInsets.all(10),
                            child: Text(title,
                                style: Theme.of(context).textTheme.bodyLarge)),
                        Card(
                          child: ListTile(
                            title: Text(detailTitle),
                            subtitle: Text(detailActiviyName,
                                style: Theme.of(context).textTheme.bodySmall),
                            trailing: TextButton(
                                child: Text('open'.tr),
                                onPressed: () {
                                  Navigator.of(context).pop();
                                  openWork(work);
                                }),
                          ),
                        ),
                        Expanded(
                            flex: 1,
                            child: ListView(
                                children: workLogList.map((e) {
                              var time = e.arrivedTime;
                              if (time == null || time.isEmpty) {
                                time = e.fromTime;
                              }
                              if ((time?.length ?? 0) > 16) {
                                time = time!.substring(0, 16);
                              }
                              var title = e.fromActivityName ?? '';
                              var routeName = e.routeName;
                              var imageName = 'icon_process_pass.png';
                              List<String> identities = [];
                              if (e.taskList != null &&
                                  e.taskList!.isNotEmpty) {
                                for (var task in e.taskList!) {
                                  identities
                                      .add(task.identity!.split('@').first);
                                }
                              }
                              if (e.taskCompletedList != null &&
                                  e.taskCompletedList!.isNotEmpty) {
                                for (var taskcompleted
                                    in e.taskCompletedList!) {
                                  identities.add(
                                      taskcompleted.identity!.split('@').first);
                                }
                              }
                              if (e.fromActivityType == 'begin') {
                                routeName = '';
                                imageName = 'icon_process_begin.png';
                              }
                              if (e.isEnd) {
                                title = e.arrivedActivityName ?? '';
                                routeName = '';
                                identities = [];
                                imageName = 'icon_process_end.png';
                              }
                              var subtitle = '';
                              if (routeName != null && routeName.isNotEmpty) {
                                subtitle = '$routeName $time';
                              } else {
                                subtitle = time ?? '';
                              }
                              return IntrinsicHeight(
                                  child: Row(
                                children: [
                                  AssetsImageView(imageName),
                                  Expanded(
                                      flex: 1,
                                      child: Column(
                                        children: [
                                          Padding(
                                              padding: const EdgeInsets.only(
                                                  left: 10,
                                                  right: 10,
                                                  top: 10,
                                                  bottom: 10),
                                              child: Row(
                                                children: [
                                                  Expanded(
                                                      flex: 1,
                                                      child: Column(
                                                        crossAxisAlignment:
                                                            CrossAxisAlignment
                                                                .start,
                                                        children: [
                                                          Text(
                                                            title,
                                                            style: Theme.of(
                                                                    context)
                                                                .textTheme
                                                                .bodyLarge,
                                                          ),
                                                          const SizedBox(
                                                              height: 5),
                                                          Text(subtitle,
                                                              style: Theme.of(
                                                                      context)
                                                                  .textTheme
                                                                  .bodySmall)
                                                        ],
                                                      )),
                                                  SizedBox(
                                                      width: 48.w,
                                                      child: Text(
                                                          identities.join(',')))
                                                ],
                                              )),
                                          // ListTile(
                                          //   contentPadding: const EdgeInsets.symmetric(vertical: 10.0),
                                          //   title: Text(title),
                                          //   subtitle: Text(subtitle,
                                          //       style: Theme.of(context)
                                          //           .textTheme
                                          //           .bodySmall),
                                          //   trailing: SizedBox(
                                          //       width: 48.w,
                                          //       child:
                                          //           Text(identities.join(','))),
                                          // ),
                                          const Spacer(),
                                          const Divider(height: 1)
                                        ],
                                      ))
                                ],
                              ));

                              // return ListTile(
                              //   title: Text(time ?? ''),
                              //   subtitle: Text(
                              //       'process_work_go_to_activity'
                              //           .trArgs([e.activityName ?? '']),
                              //       style: TextStyle(
                              //           color: Theme.of(context)
                              //               .colorScheme
                              //               .primary)),

                              // );
                            }).toList()))
                      ],
                    )));
          }));
    }
  }

  Future<void> openWork(Work work) async {
    if (work.id != null && work.id?.isNotEmpty == true) {
      await ProcessWebviewPage.open(work.id!,
          title: work.title ??
              'process_work_no_title'.trArgs(['${work.processName}']));
      onRefresh();
    }
  }

  loadDataFromServer() async {
    String searchKey = searchController.text;
    OLogger.d(
        '开始加载数据，type: $_type , lastId: $_lastId, isrefresh: $isRefresh searchKey: $searchKey ');
    Map<String, dynamic>? filter;
    if (searchKey.isNotEmpty) {
      filter = {'key': searchKey};
    }
    isLoading = true;
    if (O2NativeAppEnum.task.key == _type) {
      final list = await ProcessSurfaceService.to
          .getTaskListByPage(_lastId, body: filter);
      if (list != null) {
        if (list.isNotEmpty) {
          if (isRefresh) {
            state.dataList.clear();
          }
          state.dataList.addAll(list);
          _lastId = list[list.length - 1].id!; // 最后一个id
          state.hasMoreData = list.length >= O2.o2DefaultPageSize;
        } else {
          state.hasMoreData = false;
        }
      }
    } else if (O2NativeAppEnum.taskcompleted.key == _type) {
      final list = await ProcessSurfaceService.to
          .getTaskCompletedListByPage(_lastId, body: filter);
      if (list != null) {
        if (list.isNotEmpty) {
          if (isRefresh) {
            state.dataList.clear();
          }
          state.dataList.addAll(list);
          _lastId = list[list.length - 1].id!; // 最后一个id
          state.hasMoreData = list.length >= O2.o2DefaultPageSize;
        } else {
          state.hasMoreData = false;
        }
      }
    } else if (O2NativeAppEnum.read.key == _type) {
      final list = await ProcessSurfaceService.to
          .getReadListByPage(_lastId, body: filter);
      if (list != null) {
        if (list.isNotEmpty) {
          if (isRefresh) {
            state.dataList.clear();
          }
          state.dataList.addAll(list);
          _lastId = list[list.length - 1].id!; // 最后一个id
          state.hasMoreData = list.length >= O2.o2DefaultPageSize;
        } else {
          state.hasMoreData = false;
        }
      }
    } else if (O2NativeAppEnum.readcompleted.key == _type) {
      final list = await ProcessSurfaceService.to
          .getReadCompletedListByPage(_lastId, body: filter);
      if (list != null) {
        if (list.isNotEmpty) {
          if (isRefresh) {
            state.dataList.clear();
          }
          state.dataList.addAll(list);
          _lastId = list[list.length - 1].id!; // 最后一个id
          state.hasMoreData = list.length >= O2.o2DefaultPageSize;
        } else {
          state.hasMoreData = false;
        }
      }
    }
    isLoading = false;
  }
}
